<?php
require '../common.inc.php';


if($action == 'callback') {
	if($code) {
		include DT_ROOT.'/api/weixin/config.inc.php';
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.WX_APPID.'&secret='.WX_APPSECRET.'&code='.$code.'&grant_type=authorization_code';
		$rec = dcurl($url);
		$arr = json_decode($rec, true);
		// if($arr['openid'] && is_openid($arr['openid'])) {
		if($arr['openid']  ) {
			$openid = $arr['openid'];
			$r = $db->get_one("SELECT * FROM {$DT_PRE}weixin_user WHERE openid='$openid'");
			if($r) {
				$itemid = $r['itemid'];
				if($r['nickname']) $arr['access_token'] = ''; //如果已经有nickname则不更新 用户信息
			} else {
				$db->query("INSERT INTO {$DT_PRE}weixin_user (openid,subscribe,addtime,edittime) VALUES ('$openid','2','$DT_TIME','$DT_TIME')");
				$itemid = $db->insert_id();
			}
			if($arr['access_token']) {
				$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$openid.'&lang=zh_CN';
				$rec = dcurl($url);
				$info = json_decode($rec, true);
				$sql = "edittime=$DT_TIME";
				if(isset($info['nickname'])) {
					foreach(array('nickname', 'sex', 'city', 'province', 'country', 'language', 'headimgurl') as $v) {
						if(isset($info[$v])) $sql .= ",".$v."='".addslashes($info[$v])."'";
					}
				}
				$uSql = "UPDATE {$DT_PRE}weixin_user SET $sql WHERE itemid=$itemid";
				$db->query($uSql);
			}
			set_cookie('weixin_openid', encrypt($openid, DT_KEY.'WXID'));
			dheader('zbdy.php?action=login&reload='.$DT_TIME);
		}
	}
} else {
	set_cookie('weixin_url', $url);
	include DT_ROOT.'/api/weixin/config.inc.php';
	// $scope = $action == 'connect' ? 'snsapi_userinfo' : 'snsapi_base';
	$scope =  'snsapi_userinfo' ;
	$s_auth = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WX_APPID.'&redirect_uri='.urlencode($EXT['mobile_url'].'weixin-dy.php?action=callback').'&response_type=code&scope='.$scope.'&state=1#wechat_redirect';
	echo "string->".$s_auth;
	dheader($s_auth);
}
// dheader('zbdy.php);
?>